import GameManager from "./GameManager";

export default class AIPlayerContorller extends Laya.Script {

    constructor() { 
        super(); 
        /** @prop {name:ball, tips:"提示文本", type:Node, default:null}*/
        /** @prop {name:cui, tips:"提示文本", type:Node, default:null}*/
        this.rig=null;
        this.minX=1000;
        this.maxX=2000;
        this.minJumpDistance=400;
        this.catJump=true;
        this.jupSpeed=-10;

        this.gameManager=null;

        this.lastX=0;       
        this.cui=null; 
        // 更多参数说明请访问: https://ldc2.layabox.com/doc/?nav=zh-as-2-4-0
    }
    reset(){
        this.gameManager.AddMyScore()
        this.owner.x=1440
        this.owner.y=850
        this.rig.setVelocity({x:0,y:0})
    }
    onAwake(){
        this.gameManager=this.owner.parent.getComponent(GameManager)
         this.rig=this.owner.getComponent(Laya.RigidBody);
         Laya.stage.on("ResetAIPlayer",this,this.reset)

    }
    onDestroy(){
        Laya.stage.off("ResetAIPlayer",this,this.reset)

    }
    onUpdate(){
        if(this.gameManager.gameOver){
            this.cui.rotation=0;
            return;
        }
        if(this.owner.y>780){
            this.catJump=true;
        }
        if(this.ball.x>this.minX&&this.ball.x<this.maxX){
            var targetX=this.ball.x
            this.owner.x=Laya.MathUtil.lerp(this.owner.x,targetX,
            Laya.timer.delta/1000*5)

            if(this.owner.x>this.lastX)
            {
                this.cui.rotation=90
            }
            else{
                this.cui.rotation=-90
            }
            this.lastX=this.owner.x

            var delX=this.owner.x-this.ball.x;
            var delY=this.owner.y-this.ball.y;
            var dis=Math.sqrt(delX*delX+delY*delY)
            if(dis<this.minJumpDistance&&this.catJump){
                this.catJump=false;
                var x=this.rig.linearVelocity.x;
                var y=this.jupSpeed-this.getRandom(1,5)
                 this.rig.setVelocity({x:x+20,y:y});
            }
        }
        else{
            this.cui.rotation=0
        }
       
    } getRandom(min,max)
        {
            var value=max-min;
            value=Math.random()*value
            return value+min;
        }
}